#!/bin/bash

source /home/shell/util.sh

# 安装函数
function install () {

    if [ "$(ostype)" == "Ubuntu" ]; then
        apt install build-essential -y
    else
        dnf install gcc gcc-c++ -y
    fi

    if [ ! -f "/usr/local/go/bin/go" ]; then
        printInfo "安装GO..."
        bash /home/shell/golang-install.sh
    fi
    source /etc/profile.d/go_lang.sh

    if [ ! -d "/usr/local/src/go-probe" ]; then
        git clone https://hub.fastgit.org/ProbeChain/go-probe.git /usr/local/src/go-probe
    fi
    cd /usr/local/src/go-probe
    git branch -a
    read -p "请选择版本[master]：" version
    version=${version:-"master"};

    if [[ "${version}" != "master" ]]; then
        git checkout -b origin/release/${version} remotes/origin/release/${version}
    fi

    go env -w GOPROXY=https://goproxy.cn
    go env -w GO111MODULE=auto

    cd /usr/local/src/go-probe/cmd/gprobe
    go build
tee /etc/profile.d/gprobe.sh<<EOF
export PATH="/usr/local/src/go-probe/cmd/gprobe:\$PATH"
EOF
    source /etc/profile.d/gprobe.sh

    bash /home/shell/nodejs-install.sh
    source /etc/profile.d/nodejs.sh
}

# 配置函数
function config(){
    read -p "指定数据目录[/home/gprobe/node1]：" data_dir
    data_dir=${data_dir:-"/home/gprobe/node1"};

    if [ ! -d "${data_dir}" ]; then
        mkdir -p ${data_dir}
    fi
    
    # gprobe --datadir ${data_dir} init /home/shell/support/probechain/genesis.json
    gprobe --datadir ${data_dir} init /home/shell/support/probechain/genesis-alone.json

    if [ ! -d "/var/log/gprobe" ]; then
        mkdir -p /var/log/gprobe
    fi

    ufw allow 40000

    firewall-addport 30000
    firewall-addport 40000
}

function run () {
    # http方式
    cd /opt
    rz
    unzip ./deploy.zip
    rm -rf ./deploy.zip
    cd /opt/deploy
    cp /usr/local/src/go-probe/cmd/gprobe/gprobe ./
    /opt/nodejs/bin/npm i
    /opt/nodejs/bin/node init
    /opt/nodejs/bin/node start
    # tail -200f /opt/deploy/nodes/node1/gprobe.log
}

function run1 () {
    /usr/local/src/go-probe/cmd/gprobe/gprobe --datadir ${data_dir} --syncmode full --ipcdisable --maxpeers 128 --rpcvhosts=* --maxpendpeers 256 \
    --gcmode archive --cache.snapshot 0 --networkid 6 --nodiscover --http.api probe,net,web3,personal,admin,miner,txpool,debug --log.debug --verbosity 5 \
    --allow-insecure-unlock --http --http.corsdomain * --http.addr 0.0.0.0 --http.port 40000 --port 30000 --unlock 0 --password ./pwd --mine --miner.threads 1
}

function rebuild () {
    git -C /usr/local/src/go-probe pull
    cd /usr/local/src/go-probe/cmd/gprobe
    go build
    cp -r /usr/local/src/go-probe/cmd/gprobe/gprobe /opt/deploy/
    pid=`ps aux|grep gprobe|grep datadir|awk '{print $2}'`;
    echo "杀进程$pid"
    kill -15 $(pidof gprobe)
    cd /opt/deploy/
    /opt/nodejs/bin/node start
    tail -200f /opt/deploy/nodes/node1/gprobe.log
}

# 运行安装和配置
install && config && run